﻿using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Security;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using System.Web;
using RrslLite.Net.Contracts;
using RrslLite.Net.Messages;

namespace App.Host.Web
{
    //[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    //[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
	public class WcfMessageService : RrslLite.Host.WcfMessageService, IWcfMessageService
    {
		private readonly static NamedPipeServerStream pipeStream = null;
		static WcfMessageService()
		{
			pipeStream = new NamedPipeServerStream("testpipe-WcfMessageWervice", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None);
		}

        public override Message[] InvokeOperations(params Message[] messages)
        {
            if (!OperationContext.Current.ServiceSecurityContext.WindowsIdentity.IsAuthenticated)
                throw new SecurityException();

            OperationContext.Current.OperationCompleted += Current_OperationCompleted;

            return base.InvokeOperations(messages);
        }

        void Current_OperationCompleted(object sender, EventArgs e)
        {

        }
		protected override void OnExeption(Exception e, Message message)
		{
			try
			{
				//Check for LogExceptionsTEST
				if (e.InnerException.Message == Business.Party.ExceptionConstants.ExceptionMessage)
				{
					if (pipeStream != null)
					{
						pipeStream.WaitForConnection();

						byte[] sendMessage = new UTF8Encoding().GetBytes(Business.Party.ExceptionConstants.MessageFromServer);
						pipeStream.Write(sendMessage, 0, sendMessage.Length);
						pipeStream.Disconnect();
					}
				}
			}catch(Exception ex)
			{
				;
			}
		}
    }

    public class WcfDuplexMessageService : RrslLite.Host.WcfDuplexMessageService
    {
        public override void InvokeOperations(params Message[] messages)
        {
            if (!OperationContext.Current.ServiceSecurityContext.WindowsIdentity.IsAuthenticated)
                throw new SecurityException();

            base.InvokeOperations(messages);
        }
    }
}